Ext.form.Field.prototype.initComponent = function(){       
    if(this.allowBlank==false){
        this.fieldLabel = this.fieldLabel + '<font color=red>*</font>';
    }
    Ext.form.Field.superclass.initComponent.call(this);
    this.addEvents(
        'focus',
        'blur',
        'specialkey',
        'change',
        'invalid',
        'valid'
    );
}

Ext.override(Ext.grid.RowSelectionModel, {
	deselectRow : function(index, preventViewNotify){
		
		//Gfa.widgets.BaseGrid 行点击事件
		var vBeforeRowSelectFunc = this.grid.beforeRowSelectFunc;
		if(vBeforeRowSelectFunc){
			var result = eval(vBeforeRowSelectFunc + '()');
			if(! result == true){
				return;
			}
		}
		//end  Gfa.widgets.BaseGrid 行点击事件
		
        if(this.isLocked()) return;
        if(this.last == index){
            this.last = false;
        }
        if(this.lastActive == index){
            this.lastActive = false;
        }
        var r = this.grid.store.getAt(index);
        if(r){
            this.selections.remove(r);
            if(!preventViewNotify){
            	 this.grid.getView().onRowDeselect(index);
            }
            this.fireEvent("rowdeselect", this, index, r);
            this.fireEvent("selectionchange", this);
        }
    },
    /**
     * add by baodk
     * 
     */
    selectAll : function(){
    	//用于表示当前动作是全选
    	var flag = true;
        if(this.isLocked()) return;
        this.selections.clear();
        for(var i = 0, len = this.grid.store.getCount(); i < len; i++){
            this.selectRow(i, true, null, flag);
        }
    },
    
    /**
     * 	add by baodk
     * 	解决全选很慢的问题
     * 	flag 判断当前是否是全选
     */
    selectRow : function(index, keepExisting, preventViewNotify, flag){
        if(this.isLocked() || (index < 0 || index >= this.grid.store.getCount()) || this.isSelected(index)) return;
        var r = this.grid.store.getAt(index);
        // 是全选，不执行相关的行选择事件
        if(flag){
        	if(r){
        		if(!keepExisting || this.singleSelect)
        			this.clearSelections();
        	}
        	this.selections.add(r);
            this.last = this.lastActive = index;
            if(!preventViewNotify){
                this.grid.getView().onRowSelect(index);
            }
        }else{
        	if(r && this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false){
                if(!keepExisting || this.singleSelect){
                    this.clearSelections();
                }
                this.selections.add(r);
                this.last = this.lastActive = index;
                if(!preventViewNotify){
                    this.grid.getView().onRowSelect(index);
                }
                this.fireEvent("rowselect", this, index, r);
                this.fireEvent("selectionchange", this);
            }
        }
    }
});




Ext.namespace("Gfa.widgets");
Gfa.widgets.BaseGrid = function(config){
	//默认初始化
	//默认分页
	if(config.paging == undefined){
		config.paging = true ;
	}
	
	//默认分页栏在下方
	if(config.pagingPos == undefined){
		config.pagingPos = 'bottom' ;
	}
	
	//默认分页列表
    if(!config.pageSizeList){
        config.pageSizeList = Gfa.GlobalConstant.PAGESIZE_LIST ;
        
     }
     
     if(!config.pageSize){
    	config.pageSize = Gfa.GlobalConstant.PAGESIZE ;
     }
     
     //默认可以多选
     if(config.multiSelect==undefined){
     	config.multiSelect = true ;
     }

	if(!config.reader){
		CommonWebService.getQueryDataItemFields(config.queryObjectName ,{
			callback:function(data){
				config.reader = new Gfa.data.DwrReader({},data) ;
			} , 
			async : false
		}) ;
	}     
	
	if(!config.store){
		config.store =  new Gfa.data.Store({
					proxy : new Gfa.data.DwrProxy(CommonService),    
					reader : config.reader
		    	});
	}
	
	if(config.paging){
		// 当displayPagingInfo设置为false时才不显示分页信息, 默认为true
		var displayInfo = (config.displayPagingInfo === false) ? false : true;
		var params = {};
		if(config.allowSelectPageSize || config.showSortingAll 
				|| (config.showExportToExcel===undefined?ProjConfigParam.SHOW_EXPORT_TO_EXCEL:config.showExportToExcel)
			){
			if(config.showSortingAll){
				params.showSortingAll = config.showSortingAll;
			}
		   	this.pagingToolbar = Ext.applyIf(new Gfa.widgets.PagingToolbar({store:config.store, 
										  displayInfo:displayInfo, 
										  beforePageText:i18n.message.beforePageText,
										  afterPageText:i18n.message.afterPageText,
										  displayMsg:i18n.message.displayMsg,
										  pageSize: config.pageSize ,
										  showExportToExcel : config.showExportToExcel ,
										  showExportAllToExcel : config.showExportAllToExcel
			}), params);

			this.pagingToolbar.grid = this ;									  
		}
		else{
		   	this.pagingToolbar = new Ext.PagingToolbar({store:config.store, 
										  displayInfo:displayInfo, 
										  beforePageText:i18n.message.beforePageText,
										  afterPageText:i18n.message.afterPageText,
										  displayMsg:i18n.message.displayMsg,
										  pageSize: config.pageSize
			}) ; 		
		}
		
		if(config.pagingPos == 'bottom')										 
			config.bbar = this.pagingToolbar ;	
		else if(config.pagingPos == 'top')	
			config.tbar = this.pagingToolbar ;	
		else if(config.pagingPos == 'all')	{
			if(config.allowSelectPageSize){
			   	this.pagingToolbar2 = new Gfa.widgets.PagingToolbar({store:config.store, 
											  displayInfo:displayInfo, 
											  beforePageText:i18n.message.beforePageText,
											  afterPageText:i18n.message.afterPageText,
											  displayMsg:i18n.message.displayMsg,
											  pageSize: config.pageSize
				}) ; 
													  
				this.pagingToolbar2.grid = this ;									  
			}
			else{
			   	this.pagingToolbar2 = new Ext.PagingToolbar({store:config.store, 
											  displayInfo:displayInfo, 
											  beforePageText:i18n.message.beforePageText,
											  afterPageText:i18n.message.afterPageText,
											  displayMsg:i18n.message.displayMsg,
											  pageSize: config.pageSize
				}) ; 		
			}
											  	
			config.bbar = this.pagingToolbar ;
			config.tbar = this.pagingToolbar2 ;		
		}
	}
	/**/
	
	var sm ; 
	if(config.multiSelect){
		sm= new Ext.grid.CheckboxSelectionModel({singleSelect:false}); 
		config.cm.config.unshift(sm);	
	}
	else{
		sm = new Ext.grid.RowSelectionModel({singleSelect:true}) ;
			
	}
	config.sm = sm ;

	/**/
	Gfa.widgets.BaseGrid.superclass.constructor.call(this,config);

	
};


Ext.extend(Gfa.widgets.BaseGrid , Ext.grid.EditorGridPanel ,{
	//必须指定属性
	queryObjectName:null,//指定查询对象
	reader:null,
	cm:null,
	
	//可配置属性
	whereCondition:null,//指定查询条件
	dwrService : null,//指定保存对应的service(如果不存在保存,可以不指定)
	dwrMethod : null,//指定保存对应的方法(如果不存在保存,可以不指定)
	queryPanel:null ,//指定查询面板(如果不存在保存,可以不指定)
	
	// @added by GXl
	searchFormId : null,// @added gxl, 2009-06-16 AM，指定JSP页面中查询FORM的id
	searchBtnId : null, // @added gxl, 2009-06-16 AM 10:37，指定JSP页面中查询按钮的id
	saveBtnId : null,	// @added gxl, 2009-06-16 PM 13:48，指定JSP页面中保存按钮的id
	newBtnId : null,	// @added gxl, 20090616PM1940，指定JSP页面中新建按钮的ID
	deleteBtnId : null, // @added gxl, 20090616PM1940，指定JSP页面中删除按钮的ID
	cancelBtnId : null, // @added gxl, 20090616PM1958，指定JSP页面中取消按钮的ID
	editBtnId : null,	// @added linc, 20100114AM1121, 指定JSP页面中编辑按钮的ID
	exportToExcelBtnId : null ,
	exportAllToExcelBtnId : null ,
	showExportToExcel : false , //是否显示导出按钮
	showExportAllToExcel : false ,//是否显示导出全部按钮
	showSortingAll : true ,//是否显示所有数据排序按钮
	
	editFormId : null, 	// @added gxl, 20090617AM10:10，指定表格下方编辑表单的ID
	editDivId : null, 	// @added xiezm, 20101231AM10:32，编辑区域DIV必须包含编辑字段，也可以是 editFormId
	editingRowIdx : -1,
	tabEnableEditor : false,	// @added xiezm, 20111128PM15:18，tab激活编辑单元格
	
	parentId : null,			// @added gxl, 20090617PM1605，指定主表主键名，用于多表跳转至编辑页面用
	editPageLocation : null, 	// @added gxl, 20090617PM1606，指定编辑页面地址，用于多表跳转使用
	parentHiddenId : null,		// @added gxl, 20090617PM1648，指定编辑页面中保存主表主键的隐藏控件的ID
	
	parentEditFormId : null,	// @added gxl, 20090617PM1718，指定
	parentDwrService : null,	
	parentLoadMethod : null,
	parentSaveMethod : null,
	
	foreignId : null, 		// @added gxl, 20090617PM49，指定子表中外键的名称
	childId : null, 		// @added gxl, 20090617PM1841，指定子表主键名
	childSetName : null, 	// @added gxl, 20090617PM1842，指定子表集合名
	parentName : null,		// @added gxl, 20090617PM1940，指定子表中主表实体的名称，用于双向关联的情况
	
	newParentBtnId : null, 	// @added gxl, 20090617PM2003，指定主子表查询界面中新增主表记录的按钮ID
	afterLoadFunc : null,	// @added by xiezm 20110216，grid load完后执行
	beforeLoadFunc : null,	// added by Linc, 20100118 可自定义加载数据的配置或操作
	beforeLoadDwrConfig : null, // added by huanglp, 20100318 自定义加载数据的Service、方法、参数
	beforeSaveFunc : null,		// @added gxl, 20090618AM0107，保存主表前可以执行的JS方法名
	afterSaveFunc : null,		// @added linc, 20100223，保存主表后可以执行的JS方法名
	beforeNewChildFunc : null,  // @added liuzg, 保存子表前执行的JS方法名
	beforeNewRowFunc : null,	// @added xiezm, 主表新增前执行的JS方法
	beforeRowSelectFunc : null, // @added Cloud, 点击其他行前执行JS方法名
	selectFirstRowOnLoad : true, // added by Linc, 是否在load后选择第一条数据, 默认为ture
//	_isFirstSelect : false,
	
	// 弹出编辑的情况
	winId : null,				// @added gxl, 20090618PM1712，弹出窗口ID
	winFormId : null,			// @added gxl, 20090618PM1712，弹出窗口里面表单的ID
	winSaveBtnId : null,		// @added gxl，20090618PM1712，弹出窗口中保存按钮的ID
	winCancelBtnId : null,		// @added gxl，20090618PM1713，弹出窗口中取消按钮的ID
	_rowStatus : Gfa.GlobalConstant.ROWSTATUS_UNCHANGED,
	
	paging:true,//是否分页,默认分页
	pagingPos:'bottom',//分页栏的位置,可选值(bottom,top,all),默认上下都显示
	displayPagingInfo : true, //是否显示分页信息, 默认为显示
	allowSelectPageSize : true , //是否允许选择每页记录数
	pageSizeList:Gfa.GlobalConstant.PAGESIZE_LIST,//每页记录数列表,默认10,20,100
	pageSize :Gfa.GlobalConstant.PAGESIZE ,//默认每页记录数,默认10
	
	multiSelect:true,//是否允许多选,默认true
	
	orderBy:'',//默认的排序字段与方式,如'orgChnName',或	'orgChnName desc'
	sortType:'client' ,//点击表头排序的类型:client,server,默认为client
	
	fieldCodeTypes:null,//设置编码转名称
	
	beforeSearchFunc : null,// 查询前执行校验
	
	exportExcelLimit : 1000 , //导出excel的数目限制
	
	exportExcelColumnFuncs : null , //导出excel的列的转换函数,如"column1:fun1|column2:fun2"
	
	afterNewBtnFunc : null,		// @added pony, 20100318PM16:10，再新增按钮后执行用于付默认值等操作
	
	afterDelBtnFunc : null,		// @added yanjt, 20100601PM10:30，再删除按钮后执行用于付默认值等操作
	
	/**
	 * 默认的beforeLoad方法
	 * @param {} store
	 * @param {} options
	 */
	defaultBeforeLoadFunc : function(store, options){
		if(options.params === undefined)
    		options.params = {};
    		
    	if(options.params.start === undefined){
		    options.params.start = 0;
		}

		if (this.beforeLoadDwrConfig) {//huanglp
			var dwrConfig = eval(this.beforeLoadDwrConfig + '()');
			store.proxy.DWR = dwrConfig.service;
			options.params.dwrMethod = dwrConfig.method;
			if (dwrConfig.params) {//没有参数则设置成null,否则[,]
				if(this.paging == true){
					if (!dwrConfig.ignorePagingParam) {//dwr参数不增加分页信息
						var _pageStart = options.params.start + 1;
						var _pageSize = options.params.limit || this.pageSize;
						var _pageIndex = (_pageStart-1)/_pageSize + 1;
						dwrConfig.params.push(_pageIndex);
						dwrConfig.params.push(_pageSize);
					}
					if (this.showSortingAll) {
						if (!dwrConfig.ignoreSortingAllParam) {//dwr参数不增加排序参数
							dwrConfig.params.push(this.orderBy ? this.orderBy : {});
						}
					} else {
						if (this.orderBy) {
							dwrConfig.params.push(this.orderBy);
						}
					}
				} else {
					if (this.orderBy) {
						dwrConfig.params.push(this.orderBy);
					}
				}
			} else {
				dwrConfig.params = null;
			}
			options.params.dwrArguments = dwrConfig.params;
			options.callback = dwrConfig.callback ? dwrConfig.callback : Ext.emptyFn();
		} else {
			var listType='';
			if(this.paging == true){
				listType='page';
			}else{
				listType='list';
			}
			var queryInfo = {
				queryObjectName : this.queryObjectName,
				entityAlias : null,
				listType : listType,
				conjunctionType : 'and'
			} ;
			if(this.isDistinct == true){
				queryInfo.distinct = true;
			}
			if(this.paging == true){
				var _pageStart = options.params.start + 1;
				var _pageSize = options.params.limit || this.pageSize;
				queryInfo.pageStart = _pageStart;
				queryInfo.pageSize = _pageSize;
			}
			/**
			 * @author liuzg 2009-07-30
			 */
			if(this.whereCondition){
				queryInfo.whereCondition = this.whereCondition;
			}
			/**
			 * for jsp
			 * @author gxl
			 * @date 2009-06-16 AM
			 */ 
			if(this.searchFormId){
				queryInfo.fields = Gfa.ConditionHelper.buildCondition4Form(this.searchFormId);
			}
			if(this.orderBy != ''){
				queryInfo.orderByProps = this.orderBy;
			}
			
			/**
			 * 多表编辑中子表表格取数
			 */
			if(this.parentHiddenId && Ext.get(this.parentHiddenId)){
				var queryField = {};
				if(this.foreignId){
					var vParentHiddenId = this.parentHiddenId;
					queryField.fieldName = this.foreignId;
					var foreignIdValue = Ext.get(vParentHiddenId).getValue();
					if(foreignIdValue == ''){
						foreignIdValue = '_';
					}
					queryField.fieldValueString = foreignIdValue;
					queryField.condition = 'eq';
				} else {
					var vParentHiddenId = this.parentHiddenId;
					var foreignIdValue = Ext.get(vParentHiddenId).getValue();
					queryInfo.entityAlias = 'entity'
					queryInfo.whereCondition = 'entity.' + this.parentName + '.' + this.parentId + '=\'' + foreignIdValue + '\'';
				}
				if(queryInfo.fields){
					queryInfo.fields.push(queryField);
				} else {
					queryInfo.fields = [queryField];
				}
			}
	
			store.proxy.DWR = CommonService;
			options.params.dwrMethod = "findByQueryInit";
			options.params.dwrArguments = [queryInfo, []];
			/*options.callback = function(o, options, success){
			}*/
		}

		// 主表编辑面板装载数据
		if(this.parentEditFormId){
			this.loadParent();
		}		
    },
	
	//可配置属性:end
	
	regEvent :function(){
		this.on('sortchange', this.sortChanged, this);
		
		this.on('headerclick', this.headerClick, this);
		
		this.store.on('beforeSave', function(store, params){
					store.proxy.DWR = eval(this.dwrService);
				    params.dwrMethod = this.dwrMethod;
				}, this);
		
		if (this.beforeLoadFunc != null) {
			this.store.on('beforeload', eval(this.beforeLoadFunc), this);
		} else {
	    	this.store.on('beforeload', this.defaultBeforeLoadFunc, this);
		}
	    
	    this.store.on('load',function(){
	    	FormUtils.clearForm(this.editFormId);
	    	/**表单数据被清除后，必须隐藏 editForm Div，防止触发beforeRowSelect事件验证空数据**/
	    	this.showEditFormDiv(false);
	    	this.editingRowIdx = -1;
//	    	this._isFirstSelect = true;
	    	if (this.selectFirstRowOnLoad) {
	    		this.selectRow(0);
	    	}
	    	if (this.afterLoadFunc) {
	    		eval(this.afterLoadFunc + '()');
	    	}
	    	if(this.tabEnableEditor && this.tabEnableEditor === true){
	    		var _this = this;

	    		$("#"+_this.id).find("td.x-grid3-col.x-grid3-cell").live("focusin",function(){
	    			_this.focusCol = $(this).index();
	    			_this.focusRow = $(this).parents("div[rowIndex]").index();
	    			if(_this.focusCol > -1 && _this.focusRow > -1){
	    				_this.startEditing(_this.focusRow, _this.focusCol);
	    			}
	    		})
	    	}
	    },this);
		
	    // 表格行点击事件
	    if(this.editFormId){
		    // 如果有设置编辑区表单id(即表格下方编辑的情况)
	    	this.on('rowclick', this.rowClick, this);
	    	this.selModel.on('beforerowselect',this.beforeRowSelect,this);
		    this.selModel.on('rowselect', this.refreshRowData, this);
	    } else {
	    	this.selModel.on('rowselect', this.refreshBtnStatus, this);
	    }
	    
	    // 表格行双击事件
	    if(this.parentId && this.editPageLocation){
	    	// 如果有设置主表ID及编辑页面地址
	    	this.on('rowDblClick', this.jump2EditPage, this);
	    } else if(this.winId){
	    	this.on('rowDblClick', this.editWinAction, this);
	    }
	    
	    // 按钮
	    if(this.searchBtnId && Ext.get(this.searchBtnId)){
	    	Ext.get(this.searchBtnId).on('click', function(){
	    		this.showEditFormDiv(false);	    		
	    		if(this.beforeSearchFunc){
	    			if(!(eval(this.beforeSearchFunc+'()') == false)){
	    				this.store.load();
	    			}
	    		} else {
	    			this.store.load();
	    		}
	    	},this);
	    }
	    
	    var vBeforeSaveFunc = this.beforeSaveFunc;
	    var vAfterSaveFunc = this.afterSaveFunc;
	    if(this.saveBtnId && Ext.get(this.saveBtnId)){
	    	// 主子表
	    	if(this.parentEditFormId){
	    		Ext.get(this.saveBtnId).on('click', this.saveParentAndChildren, this);
	    	} else {
		    	Ext.get(this.saveBtnId).on('click', function(){
		    		var selRowNum=this.selModel.lastActive;
		    		this.selModel.fireEvent('rowselect', this.selModel,-1, null);
		    		this.selModel.fireEvent('rowselect', this.selModel,selRowNum, null);
		    		if(vBeforeSaveFunc){
		    			var result = eval(vBeforeSaveFunc + '()');
		    			if(result == false){
				    		return;
		    			}
		    		}
		    		

					/*新增修改保存不刷新*/
		    		var addedRecords = []; // 新增的数据
		    		var modifiedRecords = []; // 修改的数据
		    		Ext.each(this.store.modified, function(rec){
		    			if(rec.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_DELETED){
			    			if(rec.data.IDValue == 'undefined' || rec.data.IDValue == null || rec.data.IDValue == ''){
			    				rec.data.rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
			    				addedRecords.push(rec);
			    			} else {
			    				rec.data.rowStatus = Gfa.GlobalConstant.ROWSTATUS_MODIFIED;
			    				modifiedRecords.push(rec);
			    			}
		    			}
		    		});
		    		var _store = this.store; 
		    		var _grid = this;
		    		var lstChangeData = this.store.getChangedData();
		    		// fire save action
		    		var dwrArgs = [];
	        		dwrArgs.push(lstChangeData);
	        		if (this.parentHiddenId && Ext.get(this.parentHiddenId)){
	        			var _parentId = Ext.get(this.parentHiddenId).getValue();
	        			dwrArgs.push(_parentId);
	        		}
	        		dwrArgs.push({
	        			preHook : function(){_grid.loadMask.show();},
	        			postHook : function(){_grid.loadMask.hide();},
						callback : function(result) {
							if(result && result.length>0){
								var newDatas = [];
								var bool = -1;
								for (var i = 0; i < result.length; i++) {
									for (var j = 0; j < modifiedRecords.length; j++) {
										if(result[i].IDValue == modifiedRecords[j].data.IDValue){
											if (modifiedRecords[j].data.rowStatus == Gfa.GlobalConstant.ROWSTATUS_MODIFIED) {
												modifiedRecords[j].data = result[i];
												modifiedRecords[j].commit();
												bool = j;/*result.remove(result[i]);*/
												break;
											}
										}
									}
									if(bool == -1)
										newDatas.push(result[i]);
									bool = -1;
								}
								for (var j = 0; j < addedRecords.length; j++) {
									_store.remove(addedRecords[j]);
								}
								for (var j = 0; j < newDatas.length; j++) {
									_store.insert(0, _store.createNewRecord(newDatas[j]));
								}
								_grid.view.refresh();
								//_grid.editingRowIdx = -1;
						    	_grid.selectRow(0);
							}
							if (vAfterSaveFunc) eval(vAfterSaveFunc + '()');
							_grid.store.load();
						}
					});
					eval(this.dwrService)[this.dwrMethod].apply(eval(this.dwrService), dwrArgs);
		    	},this);
	    	}
	    }
	    if(this.newBtnId && Ext.get(this.newBtnId)){
	    	Ext.get(this.newBtnId).on('click', this.newAction,this);
	    }
	    if(this.deleteBtnId && Ext.get(this.deleteBtnId)){
	    	Ext.get(this.deleteBtnId).on('click', this.deleteRecords,this);
	    }
	    if(this.cancelBtnId && Ext.get(this.cancelBtnId)){
	    	Ext.get(this.cancelBtnId).on('click', this.cancel,this);
	    }
	    if(this.newParentBtnId && Ext.get(this.newParentBtnId)){
	    	Ext.get(this.newParentBtnId).on('click', this.jump2NewPage, this);
	    }
	    if(this.winId && Ext.get(this.winId)){
	    	Ext.getCmp(this.winId).closeAction = 'hide';
	    }
	    /**
	     * 将 “if(this.winSaveBtnId && Ext.get(this.winSaveBtnId)){” 改为  “if(this.winSaveBtnId)”
	     * “winSaveBtnId”是包含在DIV“winId”中的，“winId”需要通过按钮"newBtnId"打开，“Ext.get(this.winSaveBtnId)”elements才能存在，条件才成立。
	     * 否则对“winSaveBtnId”注册事件失败，无法生效。
	     */
	    if(this.winSaveBtnId){
	    	Ext.getCmp(this.winSaveBtnId).on('click', this.winSaveAction, this);
	    }
	    /**
	     * 将 “if(this.winCancelBtnId && Ext.get(this.winCancelBtnId)){” 改为  “if(this.winCancelBtnId)”
	     * “winCancelBtnId”是包含在DIV“winId”中的，“winId”需要通过按钮"newBtnId"打开，“Ext.get(this.winCancelBtnId)”elements才能存在，条件才成立。
	     * 否则对“winCancelBtnId”注册事件失败，无法生效。
	     */
	    if(this.winCancelBtnId){
	    	Ext.getCmp(this.winCancelBtnId).on('click', this.winCancelAction, this);
	    }
	    if(this.exportToExcelBtnId && Ext.get(this.exportToExcelBtnId)){
	    	Ext.get(this.exportToExcelBtnId).on('click', this.exportToExcel, this);
	    }	
	    if(this.exportAllToExcelBtnId && Ext.get(this.exportAllToExcelBtnId)){
	    	Ext.get(this.exportAllToExcelBtnId).on('click', this.exportAllToExcel, this);
	    }
	    this.showEditFormDiv(false);   
	} ,
	
	// 使grid里的文字可选 added by linc 100224
	viewConfig : {
		templates : {
			cell : new Ext.Template(
				'<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',
				'<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',
				'</td>')
		}
	} ,
	
	initComponent : function(){
        Gfa.widgets.BaseGrid.superclass.initComponent.call(this);
		this.regEvent();	
        this.setColumnModelRender() ;
    } ,
    
    setColumnModelRender : function(){
    	if(this.fieldCodeTypes){
    		for(var prop in this.fieldCodeTypes){
    			for(var i = 0;i<this.colModel.getColumnCount();i++){
    				if(prop == this.colModel.config[i].dataIndex){
    					this.colModel.setRenderer(i ,this.selectCodeHandler(this.fieldCodeTypes[prop],prop,this) ) ;
    				}
    			}
    		}
    	}
    }, 
    
	getSelections : function(){
		if (!this.selModel.hasSelection()) 
			return;

        return this.selModel.getSelections();
	},  
	newAction : function(){
//		this._isFirstSelect = false;
//		if(this.editingRowIdx >= 0){
//			var vBeforeSaveFunc = this.beforeSaveFunc;
//			if(vBeforeSaveFunc){
//				var result = eval(vBeforeSaveFunc + '()');
//				if(result == false){
//					return;
//				}
//			}
//		}

		if(this.getSelected()){
			var vBeforeNewRowFunc = this.beforeNewRowFunc;
			if(vBeforeNewRowFunc){
				var result = eval(vBeforeNewRowFunc + '()');
				if(! result == true){
					return;
				}
			}
		}
		this.showEditFormDiv(true);
		
		if(this.parentHiddenId && this.getSelected()){
    		// 子表校验
			var vBeforeNewChildFunc = this.beforeNewChildFunc;
			if(vBeforeNewChildFunc){
				var result = eval(vBeforeNewChildFunc + '()');
				if(! result == true){
					return;
				}
			}
		}
		// 主子表
//		if(this.parentEditFormId){
			//this.refreshRowData(null, -1, null);
//		}
		this.store.insertNewRecord();
		this.editingRowIdx = this.editingRowIdx + 1;
		this.selectRow(0);
    	if(this.afterNewBtnFunc){
    		eval(this.afterNewBtnFunc + '()');
    	}
    	if(this.winId && Ext.getCmp(this.winId)){
    		if(this.winFormId && Ext.getCmp(this.winFormId)){
    			if(Ext.getCmp(this.winFormId).form){
	    			Ext.getCmp(this.winFormId).form.reset();
    			}
    		}
    		Ext.getCmp(this.winId).show();
    		this._rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
    	}
    	this.refreshBtnStatus();
	},
	deleteRecords : function(){
		if(this.store.isDirty()){
			Ext.Msg.alert(i18n.message.prompt, i18n.message.saveBefore);
			return;
		}
		
		var records = this.getSelections();
		var deletedRecords = [];
		
		if(records){
			Ext.Msg.confirm(i18n.message.prompt, i18n.message.ifDelete, function(btn, text){
        		if(btn === 'yes'){
		        	/*for(var i=0; i<records.length; i++){
		        		var record = records[i];
		        		
		        		if(record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED)
		                	this.store.remove(record);
		                else{
		                	record.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_DELETED);
		                	deletedRecords.push(record);
		                }
		        	}

		        	if(this.store.isDirty()){
		        		if (this.parentHiddenId){// 子表删除
		        			var _parentId = Ext.get(this.parentHiddenId).getValue();
		        			this.store.save([_parentId]);
		        		} else {
		        			this.store.save();
		        		}
		        		//this.store.load(); fixed by hlp:点击保存调用两次findByQueryInit.dwr
		        	}*/

        			/*删除不刷新*/
		        	for(var i=0; i<records.length; i++){
		        		var record = records[i];
	                	if(record.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_ADDED){
	                		record.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_DELETED);
	                		deletedRecords.push(record.data);
	                	}
	                	this.store.remove(record);
		        	}
		        	if(deletedRecords.length > 0){
		        		var dwrArgs = [];
		        		var _grid = this;
		        		dwrArgs.push(deletedRecords);
		        		if (this.parentHiddenId && Ext.get(this.parentHiddenId)){// 子表删除
		        			var _parentId = Ext.get(this.parentHiddenId).getValue();
		        			dwrArgs.push(_parentId);
		        		}
		        		dwrArgs.push({callback : function (){
		        			_grid.showEditFormDiv(false);
				        	_grid.editingRowIdx = -1;
				        	_grid.view.refresh();
				        	_grid.selectRow(0);
				        	if(_grid.afterDelBtnFunc){
								eval(_grid.afterDelBtnFunc + '()');
							}
				        	_grid.store.load();
		        		}});
			        	eval(this.dwrService)[this.dwrMethod].apply(eval(this.dwrService), dwrArgs);
		        	}
        		}
        	}, this);
		}
	} ,
	getSelected : function(){
		if (!this.selModel.hasSelection()) 
			return;

        return this.selModel.getSelected();
	}  ,
	
	selectRow : function(row) {
		if (this.selModel.select)// cellSelection
			this.selModel.select(row, 0);
		else
			this.selModel.selectRow(row);
	},
	
	syncPagingToolbar : function(current){
		if(current == this.pagingToolbar && this.pagingToolbar2){
			other == this.pagingToolbar2 ;
		}
		else if(current == this.pagingToolbar2 && this.pagingToolbar){
			other = this.pagingToolbar ;
		}
		else{
			return ;
		}
		
		other.comboPagesize.setValue(this.pageSize) ;
		other.pageSize = this.pageSize ;
		other.bind(this.store) ;
		
	}, 
	
	selectCodeHandler:function(fieldType, fieldName ,scope){
		return function(value,metadata ,record){
			var store = scope.store;			
			if(store.selectCodeValues != null){
				if(store.selectCodeValues[fieldType] != null && store.selectCodeValues[fieldType][value]!=undefined)
					return store.selectCodeValues[fieldType][value];
				else
					return 
						record.data[fieldName] ;
			}
			
			return value;
		}
	},
	
	sortChanged : function(grid, sortInfo){
		if(this.sortType == Gfa.GlobalConstant.SORT_TYPE_SERVER){
			this.orderBy = sortInfo.field + " " + sortInfo.direction;
			this.store.load();
		} else {
			this.editingRowIdx = this.store.indexOf(this.getSelected());	
		}
		this._isFireSortEvent = false;
	},
	

	headerClick : function(grid, columnIndex, event){
		this._isFireSortEvent = true;
	},
	
	//-----------------------@added gxl，20090617
	cancel : function(){
		this.showEditFormDiv(false);
		
		var records = this.getSelections();
		
        if(records){
        	for(var i=0; i<records.length; i++){
		        var record = records[i];
		        if(record.data.rowStatus === Gfa.GlobalConstant.ROWSTATUS_ADDED){
	                this.store.remove(record);
	        		this.editingRowIdx = -1;
		        }else{
	            	record.reject();
	            }
        	}
	        if(records.length == 1){
	        	var record = records[0];
	        	var rowIdx = this.getStore().indexOf(record);
	        	if (rowIdx != -1) {
		        	FormUtils.convertSimpleObject2Form(record.data, this.editFormId);
		        	this.selModel.fireEvent('rowselect', this.selModel, rowIdx, record);
	        	} else {
//	        		this._isFirstSelect = true;
	        		this.selectRow(0);
	        	}
	        } else {
	        	FormUtils.clearForm(this.editFormId);
	        }
        }
	},
	// 编辑区域在表格下方专用
	refreshRowData : function(selModel, rowIdx, rec) {

		if (this.editingRowIdx == rowIdx) {
			return;
		}
		var originalEditedRowIdx = this.editingRowIdx;
		if (originalEditedRowIdx != null && originalEditedRowIdx >= 0) {
			var originalEditedRec = this.store.getAt(originalEditedRowIdx);
			if (originalEditedRec) {
				var obj = {};
				FormUtils.convertSimpleForm2Object(this.editFormId, obj);
				if(this.checkUpdateId(obj, originalEditedRec.id) == false)
				{
					return;
				}
				
				this.updateObject2Record(obj, originalEditedRec);
				if (originalEditedRec.dirty
						&& originalEditedRec.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_ADDED
						&& originalEditedRec.data.rowStatus != Gfa.GlobalConstant.ROWSTATUS_DELETED) {
					originalEditedRec.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_MODIFIED);
				}
			}
		}
		
		this.editingRowIdx = rowIdx;
		
		if (rec) {
			FormUtils.convertSimpleObject2Form(rec.data, this.editFormId);

			/*2011-5-16 liucy  start*/
			var keyId=$("#keyId");
			if(keyId != null && keyId != undefined && keyId != '' )
			{
				keyId.val(rec.id);
			}
			/*2011-5-16 liucy  end*/
			
			this.showEditFormDiv(true);
		}
	},
	beforeRowSelect : function(selModel, rowIdx, rec){
		if (this.editingRowIdx == rowIdx) {
			return;
		}
		var formDiv = $('#' + this.editFormId + 'Div');
		var vBeforeRowSelectFunc = this.beforeRowSelectFunc;
		if(vBeforeRowSelectFunc && formDiv && formDiv.css('display') == 'block'){
			var result = eval(vBeforeRowSelectFunc + '()');
			if(! result == true){
				return false;
			}
		}
	},
	
	rowClick : function(grid, rowIdx, event){
		this.showEditFormDiv(true);
		this._isFireSortEvent = false;
//		this._isFirstSelect = false;
	},
	
	/*检查编辑区域的ID与grid要赋值的行的ID是否一样，如果不一样则不赋值   add liucy 20110513*/
	checkUpdateId : function(editFormObj, id){
		if(editFormObj.keyId == null || editFormObj.keyId == undefined || editFormObj.keyId == ''){
			return true;
		}
		if(editFormObj.keyId != id){
			return false;
		}
		return true;
	},
	
	// 编辑区域在表格下方专用
	// edited by gxl 20100203, 解决：改动的属性有修改的标志，切换到另一条记录，再切回来，则修改的标志消失的问题
	updateObject2Record : function(obj, record) {
		var modified = record.modified || {};
		record.beginEdit();
		var fs = record.fields;
		for (var index = 0; index < fs.length; index++) {
			var f = {};
			if (fs.items == null || fs.items == undefined) {
				f = fs[index];
			} else {
				f = fs.items[index];
			}
			var fieldValue = obj[f.name];
			if (typeof(fieldValue) != "undefined") {
				if (fieldValue == "" && record.get(f.name) == null) {
					continue;
				}
				record.set(f.name, fieldValue);
				
				var originalValue = modified[f.name];
				if(typeof(originalValue) != "undefined"){
					if(originalValue == fieldValue || 
							(originalValue == null && (fieldValue == null || fieldValue == ''))){
						delete record.modified[f.name];
					} else {
						record.modified[f.name] = originalValue;
					}
				}
			}
		}
		record.endEdit();
		return this;
	},
	// 多表
	jump2NewPage : function(){
			var url = this.editPageLocation +"?parentId=";					
			window.location.href = url;
	},
	jump2EditPage : function(){
			var selectedRecord = this.getSelected().data;
			var id = selectedRecord[this.parentId];

			var url = this.editPageLocation+"?parentId=" + id;						
			window.location.href = url;
	},
	// 多表，载入主表信息
	loadParent : function(){
		var vParentHiddenId = this.parentHiddenId;
		var vParentEditFormId = this.parentEditFormId;
		if(Ext.get(vParentHiddenId)) {
			var parentId = Ext.get(vParentHiddenId).getValue();
			if(parentId){
				eval(this.parentDwrService)[this.parentLoadMethod](parentId,function(result){
					FormUtils.convertSimpleObject2Form(result, vParentEditFormId);
				});
			} else {
				FormUtils.clearForm(vParentEditFormId);
			}
		}
	},
	// 多表，主子表一起保存
	saveParentAndChildren : function(){
		// 主表校验
		var vBeforeSaveFunc = this.beforeSaveFunc;
	    if(vBeforeSaveFunc){
			var result = eval(vBeforeSaveFunc + '()');
			if(! result == true){
				return;
			}
		}
		// 子表校验
		if(this.getSelected()){
			var vBeforeNewChildFunc = this.beforeNewChildFunc;
			if(vBeforeNewChildFunc){
				var result = eval(vBeforeNewChildFunc + '()');
				if(! result == true){
					return;
				}
			}
		}
				
		var vParentEditFormId = this.parentEditFormId;
		
		// parent
		var obj = {};
		obj = FormUtils.convertSimpleForm2Object(vParentEditFormId, obj);
		if (obj[this.parentId] != "" && obj[this.parentId] != null
				&& obj[this.parentId] != undefined) {
			//modified status
			obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_MODIFIED;
		} else {
			//new add status
			obj[this.parentId] = null;
			obj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
		}
		
		// refresh son edit form
		this.refreshRowData(null, -1, null);
		// son
		var sons = [];
		var vGridStoreDataItems = this.store.data.items;
		var vSonId = this.childId;
		var vParentName = this.parentName;
		var vForeignId = this.foreignId;
		var vParentId = this.parentId;
		Ext.each(vGridStoreDataItems, function(item) {
			var objj = item.data;
			if (objj[vSonId] == null || objj[vSonId] == undefined || objj[vSonId] == '') {
				objj.rowStatus = Gfa.GlobalConstant.ROWSTATUS_ADDED;
				objj[vSonId] = null;
				if(vParentName && (objj[vParentName] == null || objj[vParentName] == '')){
					objj[vParentName] = obj;
				}
				if(vForeignId && (objj[vForeignId] == null || objj[vForeignId] == '')){
					objj[vForeignId] = obj[vParentId];
				}
			}
			delete objj.IDValue;
			delete objj.dirty;
			sons[sons.length] = objj;
		});
		obj[this.childSetName] = sons;
		
		// real save
		var ds = this.store;
		var vAfterSaveFunc = this.afterSaveFunc;
		eval(this.parentDwrService)[this.parentSaveMethod](obj, {
			callback : function(result) {
				FormUtils.convertSimpleObject2Form(result, vParentEditFormId);
				ds.load();
				if (vAfterSaveFunc) eval(vAfterSaveFunc + '()');
			}/*,//gfa4ext-all.js中DWR错误统一处理
			errorHandler : function(errorString, exception) {
				alert(errorString + ": " + exception);
		}*/});		
	},
	// 弹出窗口保存
	winSaveAction : function(){
		var _winId = this.winId;
		var _winFormId = this.winFormId;
		var win = Ext.getCmp(_winId);
		var winForm = Ext.getCmp(_winFormId);
//		if (winForm.form&&!winForm.form.isValid()) {
//			Ext.Msg.alert(i18n.message.prompt, i18n.message.inputDataRight);
//			return false;
//		}		
		
		var vBeforeSaveFunc = this.beforeSaveFunc;
	    if(vBeforeSaveFunc){
			var result = eval(vBeforeSaveFunc + '()');
			if(! result == true){
				return;
			}
		}
		
		var editRecord = this.getSelected();
		
		if(winForm && winForm.form){
			winForm.form.updateRecord(editRecord);
		}
		
		var obj = editRecord.data;
		obj.rowStatus = this._rowStatus;
		
		var aobj = [obj]; 
		var _store = this.store;
		var vAfterSaveFunc = this.afterSaveFunc;
		eval(this.dwrService)[this.dwrMethod](aobj, function(results){
			editRecord.set('rowStatus', Gfa.GlobalConstant.ROWSTATUS_UNCHANGED);
			editRecord.commit();
			_store.load();
			if(win)
				win.hide();
			if (vAfterSaveFunc) eval(vAfterSaveFunc + '()');
		});
	},
	winCancelAction :  function(){
		this.cancel();
		if (Ext.getCmp(this.winId))
			Ext.getCmp(this.winId).hide();
	},
	editWinAction : function(){
		var win = Ext.getCmp(this.winId);
		var winForm = Ext.getCmp(this.winFormId);
		
		var editRecord = this.getSelected();

		this._rowStatus = Gfa.GlobalConstant.ROWSTATUS_MODIFIED; 
		if (win)
			win.show();
		
		if(winForm && winForm.form){
			winForm.form.loadRecord(editRecord);
		}
	},
	disableBtn : function(btnId){
		var btn = $('#' + btnId);
		if(btn){
			btn.attr('disabled','true');
		}
	},
	enableBtn : function(btnId){
		var btn = $('#' + btnId);
		if(btn){
			btn.removeAttr('disabled');
		}
	},
	refreshBtnStatus : function(){
		if(this.getSelected()){
			this.enableBtn(this.deleteBtnId);
		} else {
			this.disableBtn(this.deleteBtnId);
		}
		if(this.getSelected() || this.store.isDirty()){
			this.enableBtn(this.saveBtnId);
			this.enableBtn(this.cancelBtnId);
		} else {
			this.disableBtn(this.saveBtnId);
			this.disableBtn(this.cancelBtnId);
		}
	} ,
	
	//override
    onEditComplete : function(ed, value, startValue){
        this.editing = false;
        this.activeEditor = null;
        ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
		var r = ed.record;
        var field = this.colModel.getDataIndex(ed.col);
        value = this.postEditValue(value, startValue, r, field);
        //modify here:startValue为null,value为""时不进行替换
        if(String(value) !== String(startValue) && (!(value === "" && startValue === null ))){
            var e = {
                grid: this,
                record: r,
                field: field,
                originalValue: startValue,
                value: value,
                row: ed.row,
                column: ed.col,
                cancel:false
            };
            if(this.fireEvent("validateedit", e) !== false && !e.cancel){
                r.set(field, e.value);
                delete e.cancel;
                this.fireEvent("afteredit", e);
            }
        }
        this.view.focusCell(ed.row, ed.col);
    } ,
    
    exportToExcel: function(){
    	exportToExcel(this , this.store , false , this.exportExcelColumnFuncs) ;
    },
    
    exportAllToExcel:function (){
    	exportAllToExcel(this , this.store , this.reader , false , this.beforeExportExcelFunc.createDelegate(this) , this.exportExcelLimit 
    			, this.exportExcelColumnFuncs) ;
    },

    sortingAll : function (sortDir){
    	sortingAll(this , this.store , sortDir) ;
    },

    beforeExportExcelFunc:function(store, options){
    	if(options.params === undefined)
    		options.params = {};
    		
    	if(options.params.start === undefined){
		    options.params.start = 0;
		}
		
		var queryInfo = {
			queryObjectName : this.queryObjectName,
			entityAlias : null,
			listType : 'list',
			conjunctionType : 'and'
		} ;
		if(this.isDistinct == true){
			queryInfo.distinct = true;
		}
		/**
		 * @author liuzg 2009-07-30
		 */
		if(this.whereCondition){
			queryInfo.whereCondition = this.whereCondition;
		}
		/**
		 * for jsp
		 * @author gxl
		 * @date 2009-06-16 AM
		 */ 
		if(this.searchFormId){
			queryInfo.fields = Gfa.ConditionHelper.buildCondition4Form(this.searchFormId);
		}
		if(this.orderBy != ''){
			queryInfo.orderByProps = this.orderBy;
		}
		
		/**
		 * 多表编辑中子表表格取数
		 */
		if(this.parentHiddenId && Ext.get(this.parentHiddenId)){
			var queryField = {};
			if(this.foreignId){
				var vParentHiddenId = this.parentHiddenId;
				queryField.fieldName = this.foreignId;
				var foreignIdValue = Ext.get(vParentHiddenId).getValue();
				if(foreignIdValue == ''){
					foreignIdValue = '_';
				}
				queryField.fieldValueString = foreignIdValue;
				queryField.condition = 'eq';
			} else {
				var vParentHiddenId = this.parentHiddenId;
				var foreignIdValue = Ext.get(vParentHiddenId).getValue();
				queryInfo.entityAlias = 'entity'
				queryInfo.whereCondition = 'entity.' + this.parentName + '.' + this.parentId + '=\'' + foreignIdValue + '\'';
			}
			if(queryInfo.fields){
				queryInfo.fields.push(queryField);
			} else {
				queryInfo.fields = [queryField];
			}
		}
		
		store.proxy.DWR = CommonService;
		options.params.dwrMethod = "findByQueryInit";
		options.params.dwrArguments = [queryInfo, []];
		
		// 主表编辑面板装载数据
		if(this.parentEditFormId){
			this.loadParent();
		}
    },
    /**“新增”、"单击行" 将其显示，点击 "取消"、“查询”、“保存” 将其隐藏。**/
    showEditFormDiv : function(flag){
    	if(this.editFormId){
    		var editFormDiv = $('#' + this.editFormId+'Div');
    		
	    	if(flag){
		    	editFormDiv.show();
				editFormDiv.css('display','block');
	    	}else{
	    		editFormDiv.hide();
				editFormDiv.css('display','none');			
	    	}	
	    	this.refreshBtnStatus();
    	}
    }
});